#!/usr/bin/bash
#
# 该脚本用于远程调用执行上传的数据库脚本
# Author:konbluesky
#
# sh remote-exec-sql.sh a.sql root root jiayi backup 
# sh remote-exec-sql.sh a.sql root root jiayi import  
#
DEF_SQLPATH=/root/luxcon.sql
DEF_SQLNAME="root"
DEF_SQLPWD="root"
DEF_DATABASE="luxcon"
DEF_ACTION="backup"


_SQLFILE=$1
_MYSQLUSER=$2
_MYSQLPWD=$3
_DATABASE=$4
_ACTION=$5
# 判断文件路径
if [ $_SQLFILE ] ;then
	SQLPATH=$_SQLFILE
	echo "set SQLFILE="$SQLPATH
fi
# 判断数据库用户名
if [ $_MYSQLUSER ]; then
	DEF_SQLNAME=$_MYSQLUSER
	echo "set SQLFILE="$DEF_SQLNAME
fi
# 判断数据库密码
if [ $_MYSQLPWD ];then
	DEF_SQLPWD=$_MYSQLPWD
	echo "set DEF_SQLPWD="$DEF_SQLPWD
fi
# 判断动作
if [ $_DATABASE ];then
	DEF_DATABASE=$_DATABASE
	echo "set DEF_ACTION="$DEF_DATABASE
fi
# 判断动作
if [ $_ACTION ];then
	DEF_ACTION=$_ACTION
	echo "set DEF_ACTION="$DEF_ACTION
fi

if [ $SQLPATH ]
then
    echo $SQLPATH": is valid file for sql."
	if [[ $DEF_ACTION = "backup" ]]; then
		echo "bacup sql database........"
		# 因为导出的sql没有数据库创建语句，所以要事先加入
		#echo "CREATE SCHEMA \`"$DEF_DATABASE"\` DEFAULT CHARACTER SET utf8 ;" >> $SQLPATH | tee -a
		mysqldump -h localhost -u$DEF_SQLNAME -p$DEF_SQLPWD $DEF_DATABASE > $SQLPATH | tee -a
		echo "bacup sql database........finished!"
	else
		echo "import sql database........"
		echo "drop database \`"$DEF_DATABASE"\`;" >> tmp.sql | tee -a
		echo "CREATE SCHEMA \`"$DEF_DATABASE"\` DEFAULT CHARACTER SET utf8 ;" >> tmp.sql | tee -a
		mysqldump -h localhost -u $DEF_SQLNAME -p$DEF_SQLPWD < tmp.sql
		rm tmp.sql
		mysqldump -h localhost -u $DEF_SQLNAME -p$DEF_SQLPWD $DEF_DATABASE < $SQLPATH
		echo "import sql database........finished!"
	fi
    echo "operate is finished."
else
    echo $SQLPATH":is not file"
fi